package com.example.litehdfs.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.example.litehdfs.config.B2BServiceException;
import com.example.litehdfs.config.CodeConstant;
import com.example.litehdfs.mapper.AdminMapper;
import com.example.litehdfs.mapper.UsersMapper;
import com.example.litehdfs.model.db.Admin;
import com.example.litehdfs.model.dto.AdminLoginInfo;
import com.example.litehdfs.model.req.AdminLoginReq;
import com.example.litehdfs.service.AdminService;
import com.example.litehdfs.util.PwdUtil;
import com.example.litehdfs.util.UserCacheUtil;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.UUID;




@Service
public class AdminServiceImpl implements AdminService {

	@Autowired
	private UserCacheUtil cacheUtil;
	@Autowired
	private AdminMapper adminMapper;
	@Autowired
	private UsersMapper usersMapper;
	@Value("${server-root}")
	private String serverRoot;
	
	
	@Override
	public AdminLoginInfo adminLogin(AdminLoginReq req) {
		
		Admin admin = adminMapper.getAdmin(req.getUsername());
		if(admin == null) {
			throw new B2BServiceException("未查询到管理员");
		}
		if(req.getPassword() == null) {
			throw new B2BServiceException("密码不能为空");
		}
		
		if(!PwdUtil.validateHash(req.getPassword(), admin.getPassword())) {
			throw new B2BServiceException("密码错误");
		}
		
		//登录成功
		String token = UUID.randomUUID().toString().replace("-","");
		
		AdminLoginInfo info = new AdminLoginInfo();
		BeanUtil.copyProperties(admin, info, true);
		info.setToken(token);
		
		cacheUtil.putUserInfo(CodeConstant.ADMIN_LOGIN_TOKEN+token, info,7*24*3600);
		
		return info;
	}
	

	@Override
	public AdminLoginInfo getAdminInfo() {
		AdminLoginInfo adminInfo = cacheUtil.getAdminInfo();
		return adminInfo;
	}

	
}
